
//
//  YMSAddPictureController.swift
//  YMSWeibo
//
//  Created by 杨茂盛 on 2016/11/22.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//

import UIKit
import SnapKit
private let reuseIdentifier = "Cell"

class YMSAddPictureController: UICollectionViewController {

   lazy var pictureArray:[UIImage] = [UIImage]() //存放图片的数组
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.register(YMSAddPictureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        let delta = self.pictureArray.count == 3 ? 0 : 1
        return self.pictureArray.count + delta
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
        as! YMSAddPictureCell
        cell.pictureDelegate = self
        cell.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
        
        //判断是否是最后一行图片,如果是就赋为nil
        if indexPath.item == self.pictureArray.count {
            cell.btnImage = nil
            
        }else{
            cell.deleteBtn.isHidden = false
            cell.btnImage = self.pictureArray[indexPath.item]
  
        }
        return cell
    }
}

//--------------------------遵守协议-------------------------------------------------------------
extension YMSAddPictureController:YMSAddpictureDelegate{
    //实现代理方法
    func clickAddPicture(cell:YMSAddPictureCell?) {
        //MARK: 图片选择器
        let picView = UIImagePickerController()
        picView.isEditing = true //是否可编辑
        //设置代理
        picView.delegate = self
        picView.view.backgroundColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1)
        self.present(picView, animated: true, completion: {
    
        })
    }
    
    func clickRemovePicture(cell:YMSAddPictureCell) {
        guard  let index = collectionView?.indexPath(for: cell) else {
            return
        }
        //删除数组对应的图片
        self.pictureArray.remove(at: index.item)
        //刷新数据
        self.collectionView?.reloadData()
    }
}

//---------------------------遵守UIImagePicVc的代理方法,取出图片-----------------------------
extension YMSAddPictureController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    //此方法如果手动实现必须要自己dismiss
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //取出图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //把图片放到数组中去
        self.pictureArray.append(image.scaleImage(width: ScreenWidth))
        dismiss(animated: true, completion: {
//            //强制让collectionview刷新 不写这句话没图片
//            self.collectionView?.reloadData() //这句话要写在completion外边 否则有一种卡顿的感觉
        })
        //强制让collectionview刷新 不写这句话没图片
        self.collectionView?.reloadData() //这句话要写在completion外边 否则有一种卡顿的感觉
    }
}
//--------------------------创建协议-------------------------------------------------------------
@objc protocol YMSAddpictureDelegate:NSObjectProtocol{

    //MARK: 协议方法
    @objc optional func clickAddPicture(cell:YMSAddPictureCell?)
    @objc optional func clickRemovePicture(cell:YMSAddPictureCell)
}

//--------------------------自定义cel------------------------------------------------------------

//MARK: 自定义collectionViewCell
class YMSAddPictureCell :UICollectionViewCell{

    weak var pictureDelegate:YMSAddpictureDelegate?
    
    //设置计算型属性,一旦外界赋值,里面就进行操作
    var btnImage:UIImage? {
        didSet{
            addBtn.setImage(btnImage, for: .normal)
            deleteBtn.isHidden = btnImage == nil //没图片就隐藏删除按钮
        }
    }
    
   override init(frame: CGRect) {
    super.init(frame: frame)
    
    setUI()
    
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 搭建界面
    private func setUI(){
        //添加按钮
        addSubview(addBtn)
        //删除按钮
        addSubview(deleteBtn)
        //添加监听事件
        addBtn.addTarget(self, action: #selector(clickBtnAddPicture), for: .touchUpInside)
        deleteBtn.addTarget(self, action: #selector(clickBtnDeletePicture), for: .touchUpInside)

        deleteBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
    }
    //MARK: 添加删除按钮
    lazy var deleteBtn:UIButton = {
    let myBtn = UIButton()
        myBtn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return myBtn
    }()
    //MARK: 添加按钮
    lazy var addBtn:UIButton = {
        let myBtn = UIButton()
        myBtn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        myBtn.imageView?.contentMode = .scaleAspectFill
        return myBtn
    }()

    func clickBtnAddPicture(){
        //添加过的图片不能再选择了
        if btnImage != nil {
            return
        }
        pictureDelegate?.clickAddPicture?(cell:self)
    }
    
    func clickBtnDeletePicture(){
        pictureDelegate?.clickRemovePicture?(cell:self)
    }

}
